package com.qiaofang.applet.common.client.yxim;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.client.yxim.model.YxProperties;
import com.qiaofang.applet.common.client.yxim.model.YxMessage;
import com.qiaofang.applet.common.client.yxim.model.YxResult;
import com.qiaofang.applet.common.client.yxim.model.YxUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 网易云信IM
 * @author junze.liu
 */
@Slf4j
@Service
public class YxService {


    /**
     * 创建网易云信账号
     */
    public YxResult createAction(YxUser yxUser, YxProperties config) {
        return YxRequest.request(YxConfig.CREATA_ATION_URL, yxUser, YxResult.class, config);
    }

    /**
     * 更新网易云通信token
     */
    public static YxResult updateAction(YxUser yxUser, YxProperties config) {
        return YxRequest.request(YxConfig.UPDATE_ATION_URL, yxUser, YxResult.class, config);
    }

    /**
     * 重置网易云通信token
     */
    public static YxResult refreshTokenAtion(YxUser yxUser, YxProperties config) {
        return YxRequest.request(YxConfig.REFRESHTOKEN_ATION_URL, yxUser, YxResult.class, config);
    }

    /**
     * 更新用户名片
     */
    public static YxResult updateUinfo(YxUser yxUser, YxProperties config) {
        return YxRequest.request(YxConfig.UPDATAUINFO_ATION_URL, yxUser, YxResult.class, config);
    }

    /**
     * 批量获取用户名片
     * 每次最多200条
     */
    public static YxResult getUinfos(List<String> accids, YxProperties config) {
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        String join = String.join(",", accids.stream().map(p -> "\"" + p + "\"").collect(Collectors.toList()));
        map.add("accids", "[" + join + "]");
        JSONObject json = YxRequest.request(YxConfig.GETUINFOS_ATION_URL, map, config);
        if(json == null) {
            return null;
        }
        return JSON.parseObject(json.toJSONString(), YxResult.class);
    }

    /**
     * 聊天历史记录查询
     */
    public static YxResult querySessionMsg(YxMessage yxMessage, YxProperties config) {
        return YxRequest.request(YxConfig.QUERY_SESSION_MSG, yxMessage, YxResult.class, config);
    }
}
